package com.songlanyun.modules.marketing.seckill.controller.api;

import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.R;
import com.songlanyun.common.utils.custom.SemaphoreUtils;
import com.songlanyun.modules.account.controller.common.AbstractApiController;
import com.songlanyun.modules.exception.MarketingException;
import com.songlanyun.modules.goods.entity.Goods;
import com.songlanyun.modules.goods.entity.GoodsAuthShop;
import com.songlanyun.modules.goods.model.vo.ActivitySkuComItemVo;
import com.songlanyun.modules.goods.service.GoodsAuthShopService;
import com.songlanyun.modules.goods.service.GoodsService;
import com.songlanyun.modules.marketing.seckill.entity.SeckillActivityGoods;
import com.songlanyun.modules.marketing.seckill.model.vo.SeckillActivityAppVO;
import com.songlanyun.modules.marketing.seckill.model.vo.SeckillActivityGoodsVO;
import com.songlanyun.modules.marketing.seckill.model.vo.SeckillActivityVO;
import com.songlanyun.modules.marketing.seckill.model.vo.SeckillGoodsSkuComVo;
import com.songlanyun.modules.marketing.seckill.service.SeckillActivityGoodsService;
import org.redisson.api.RSemaphore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 秒杀活动商品表
 *
 * @author Mark
 * @email sunlightcs@gmail.com
 * @date 2020-11-23 17:30:11
 */
@RestController
@RequestMapping("api/marketing/seckillActivityGoods")
public class SeckillActivityGoodsApiController extends AbstractApiController {
    @Autowired
    private SeckillActivityGoodsService seckillActivityGoodsService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsAuthShopService goodsAuthShopService;

    /**
     * 查询该店铺中的正在秒杀的活动商品
     */
    @GetMapping("/seckilling/{shopId}")
//    @RequiresPermissions("seckill:seckillActivity:list")
    public R seckilling(@PathVariable("shopId") Long shopId) {

        SeckillActivityVO data = seckillActivityGoodsService.seckillingList(shopId);

        return R.ok().put("data", data);
    }

    /**
     * 查询该店铺中的即将秒杀的活动商品
     */
    @GetMapping("/willSeckill/{shopId}")
//    @RequiresPermissions("seckill:seckillActivity:list")
    public R willSeckill(@PathVariable("shopId") Long shopId) {
        List<SeckillActivityGoodsVO> list = seckillActivityGoodsService.willSeckillList(shopId);

        return R.ok().put("list", list);
    }


    /**
     * 查询商家某个秒杀活动商品列表
     */
    @GetMapping("/getSeckillGoodsList/{seckillId}")
//    @RequiresPermissions("seckill:seckillActivityGoods:list")
    public R list(@PathVariable("seckillId") Long seckillId) {
        List<SeckillActivityGoods> list = seckillActivityGoodsService.getBySeckillId(seckillId);

        return R.ok().put("list", list);
    }


    /**
     * 获取秒杀活动商品信息
     * 商品内容 api/goods/content/{goodsId}
     * <p>
     * 秒杀活动商品id
     */
    @GetMapping("/info/{id}")
//    @RequiresPermissions("seckill:seckillActivityGoods:info")
    public R info(@PathVariable("id") Long id) {
        SeckillActivityGoodsVO vo = seckillActivityGoodsService.getSeckillGoodsById(id, true);

        return R.ok().put("data", vo);
    }

    /**
     * 这里会涉及到
     * 商品封面图片
     * 商品售价价格（最低，最高）
     * 库存（总库存，与规格库存）
     * 商品规格表
     * 商品规格项
     * 商品当前限购
     *
     * @param seckillGoodsId
     * @return
     */
    @GetMapping("/skus/{seckillGoodsId}")
    public R getSeckillGoodsSkuList(@PathVariable("seckillGoodsId") Long seckillGoodsId) {
        SeckillActivityGoods seckillGoods = seckillActivityGoodsService.getById(seckillGoodsId);
        if (seckillGoods == null) {
            throw new RRException(MarketingException.SECKILL_ACTIVITY_GOODS_NOT_EXIST);
        }

        Goods goods = goodsService.getById(seckillGoods.getGoodsId());

        SeckillGoodsSkuComVo goodsSkuComVo = new SeckillGoodsSkuComVo();
        goodsSkuComVo.setGoods(seckillGoods);
        goodsSkuComVo.setCurrentShopId(goods.getShopId());

        //获得商品的sku集合给移动端
        List<ActivitySkuComItemVo> list = seckillGoods.loadResidualInventory();

        goodsSkuComVo.setGoodsSkuList(list);
        goodsSkuComVo.setTotalStock(seckillGoods.getResidueStockTotal());
        //商品剩余总库存
        goodsSkuComVo.setGoodsTotalStock(seckillGoods.getResidualInventory());


        /**
         * 获取经营权限
         * 可以获知，1是否是代锁，2，是否上架，3，是否审核通过
         */

        GoodsAuthShop auth = goodsAuthShopService.getAuthorizeInfo(goodsSkuComVo.getCurrentShopId(), seckillGoods.getGoodsId());
        goodsSkuComVo.setGoodsAuth(auth);


        return R.ok().put("data", goodsSkuComVo);
    }


    /**
     * APP -- 限时秒杀
     */
    @GetMapping("/flash-sale")
//    @RequiresPermissions("seckill:seckillActivityGoods:info")
    public R flashSale(@RequestParam Map<String, Object> params) {
        SeckillActivityAppVO vo = seckillActivityGoodsService.flashSale(params);
        return R.ok().put("data", vo);
    }

    /**
     * APP -- 根据开始时间查询限时秒杀
     */
    @GetMapping("/start-flash-sale")
//    @RequiresPermissions("seckill:seckillActivityGoods:info")
    public R startFlashSale(@RequestParam Map<String, Object> params) {
        SeckillActivityAppVO vo = seckillActivityGoodsService.startFlashSale(params);
        return R.ok().put("data", vo);
    }


    /**
     * TODO 测试购买秒杀活动商品
     */
//    @PostMapping("/buyGoods")
//    @RequiresPermissions("seckill:seckillActivityGoods:save")
    public R buyGoods(@RequestBody Long id) {

        SeckillActivityGoods goods = seckillActivityGoodsService.loadActivityGoodsById(id, true);

        RSemaphore semaphore = seckillActivityGoodsService.getSemaphore(goods);
        if (SemaphoreUtils.getPermits(semaphore, 1)) {//获取信号量
            //获取成功
        } else {
            //获取失败
        }

        int i = SemaphoreUtils.permitsNum(semaphore);

        SemaphoreUtils.release(semaphore, 1);
        return R.ok().put("data", i);
    }
}
